package club.web51.classroominteractiontoolsadmin.Controllers;

import club.web51.classroominteractiontoolsadmin.DO.SystemDO.Msg;
import club.web51.classroominteractiontoolsadmin.Utils.MsgUtil;
import club.web51.classroominteractiontoolsadmin.Utils.ObjectUtil;
import club.web51.classroominteractiontoolsadmin.Security.RequireToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Pageable;
import club.web51.classroominteractiontoolsadmin.DO.MainDO.Course;
import club.web51.classroominteractiontoolsadmin.Services.CourseService;

import javax.validation.Valid;

/**
 * 服务类
 * @author wxt
 * @since 1.0.0
 */
@RestController
@RequireToken
@RequestMapping("/course")
@Api(tags = "课程相关接口")
@CacheConfig(cacheNames = {"courseCache"})
public class CourseController {

    final
    CourseService courseService;

    public CourseController(CourseService courseService) {
        this.courseService = courseService;
    }

    /**
     * 根据Course的字段,自动生成条件,字段的值为null不生成条件
     * http://localhost:8080/user/?id=1
     * @param course 实体对象
     * @param pageable 分页/排序对象
     * @return 返回的是实体,里面涵盖分页信息及状态码
     */
     @GetMapping
     @Cacheable
     @ApiOperation(value = "根据条件查询课程",notes = "用于：课程查询，输入一个或多个属性参数，也可以传入分页参数")
     public Msg search(Course course,Pageable pageable) {
             return courseService.search(course, pageable);
     }
     @Cacheable
     @PostMapping
     @ApiOperation(value = "创建课程",notes = "用于：课程创建")
     public Msg create(@RequestBody @Valid Course course, BindingResult bindingResult) {
         if(bindingResult.hasErrors()){
             return MsgUtil.fail(String.valueOf(ObjectUtil.NonNullDefault(bindingResult.getFieldError().getDefaultMessage(),"发生了错误")));
         }
         return courseService.create(course);
     }
     @PutMapping
     @CachePut
     @ApiOperation(value = "动态修改课程",notes = "用于：课程信息修改")
     public Msg update(@RequestBody Course course){
         return courseService.update(course);
     }
     @CacheEvict
     @DeleteMapping("/")
     @ApiOperation(value = "删除课程",notes = "用于：课程删除，传入ID")
     public Msg delete(@ApiParam(value = "课程id") Long id){
         return courseService.delete(id);
     }
}
